package com.wm.orderService.controller;


import com.wm.commonutils.R;
import com.wm.commonutils.result.ResultCode;
import com.wm.orderService.service.PayLogService;
import com.wm.servicebase.exceptionhandle.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author sshdg
 * @since 2020-10-13
 */
@RestController
@RequestMapping("/orderService/pay")
//@CrossOrigin
@Api(tags = "支付管理")
public class PayLogController {

    @Autowired
    PayLogService payLogService;

    @ApiOperation("生成微信二维码的接口")
    @GetMapping("/createNative/{orderNo}")
    public R createWxNativePay(@PathVariable String orderNo){
        //返回的信息包括二维码地址，还需要其他的信息

        Map<String,Object> map = payLogService.createWxNativePay(orderNo);
        return R.ok().data(map);
    }

    @ApiOperation("查询订单的支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public R queryPayStatus(@PathVariable String orderNo){
        Optional.ofNullable(orderNo).orElseThrow(()-> GuliException.from(ResultCode.PARAMS_ERROR));
        Map<String,String> map =  payLogService.queryPayStatus(orderNo);

        if(CollectionUtils.isEmpty(map)){
            return R.error().message("支付出错了");
        }

        //如果返回的map不为空，通过map获取订单内容
        if("SUCCESS".equals(map.get("trade_state"))){
            //添加记录到支付表，更新订单表订单状态
            payLogService.updateOrderStatus(map);
            return R.ok().message("支付成功");
        }
        return R.ok().code(25000).message("支付中");
    }
}

